package com.zitronella.course.osseventmanager.mvc;


import com.zitronella.course.osseventmanager.domain.Position;
import com.zitronella.course.osseventmanager.domain.EventUser;
import com.zitronella.course.osseventmanager.domain.Event;
import com.zitronella.course.osseventmanager.service.PositionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: Robin
 * Date: Mar 23, 2009
 * Time: 11:41:10 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@SessionAttributes(types = Position.class)
public class RemovePositionController {


    private PositionService positionService;

    @Autowired
    public void setPositionService(PositionService positionService) {
        this.positionService = positionService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields(new String[] {"id"});
    }

    @RequestMapping(value = "/positionremove", method = RequestMethod.GET)
    public String setupForm(Model model) {
        model.addAttribute("position", new Position());
        return "position";
    }

    @RequestMapping(value = "/positionremove", method = RequestMethod.POST)
    public String saveItem(@ModelAttribute Position position, BindingResult result, HttpSession session) {
        if (StringUtils.isBlank(position.getName()))
            result.rejectValue("name", "required", "Required");

        positionService.removePosition(getEvent(session), position);
        return "redirect:/controller/home";
    }

    private Event getEvent(HttpSession session) {
        return (Event) session.getAttribute("event");
    }


}
